package com.tiance.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tiance.exception.BusinessException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/2/21
 *
 * Description：
 *
 * Modification History:
 *
 */
public class HttpUtil {

    private   static     Logger log        = LoggerFactory.getLogger(HttpUtil.class);


    private static String LOG_PREFIX ="WechatClient|微信参数===>";

     public static String get(String url) throws IOException {
      String result;

          HttpClient getHttpClient = new HttpClient();
          getHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
          GetMethod getMethod = new GetMethod(url);
         getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
         //设置期望返回的报文头编码
         getMethod.setRequestHeader("Accept", "text/plain;charset=utf-8");
          getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 8000);
          getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

          log.info(LOG_PREFIX+"开始请求微信,url="+url);
          int statusCode = getHttpClient.executeMethod(getMethod);
          log.info(LOG_PREFIX+"结束请求微信，返回结果code=" +statusCode);
          if (statusCode!=200){
              log.info(LOG_PREFIX+"请求微信失败：响应码=" + statusCode);
              throw  new BusinessException(LOG_PREFIX+"请求微信失败：响应码" + statusCode);
          }
          result = getMethod.getResponseBodyAsString().trim();
         log.info(LOG_PREFIX+"请求微信返回数据=" + result);
         if (result == null || "".equals(result)) {
              log.info(LOG_PREFIX+"请求微信失败：响应码=.响应结果不应为空");
              throw  new BusinessException(LOG_PREFIX+"请求微信失败：响应码=.响应结果为空");
          }
         result = new String(result.getBytes("ISO-8859-1"),"utf-8");

         return result;

  }
}
